package com.example.bookkeeping_book.service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.bookkeeping_book.R;
import com.example.bookkeeping_book.domain.AccountBook;
import com.example.bookkeeping_book.domain.Display;
import com.example.bookkeeping_book.utility.MyDialog;
import com.example.bookkeeping_book.utility.MySqlite;
import com.example.bookkeeping_book.utility.Utility;

import org.w3c.dom.Text;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private Button add;
    private ListView lFather;
    private TextView monthExpend;
    private TextView monthIncome;
    private TextView monthBalance;
    private TextView budget;

    private ImageView imageView;

    private double budgetMoney = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        init();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        init();
    }

    private void init() {
        add = findViewById(R.id.btn_add);
        ArrayList<Display> displays = getAllDisplay();
//        Log.i(key.size()+"", "init: ");
        monthExpend = findViewById(R.id.tv_monthExpend);
        monthIncome = findViewById(R.id.tv_monthIncome);
        monthBalance = findViewById(R.id.tv_monthBalance);
        double[] a = getMonthExpend();
        monthExpend.setText(Double.toString(a[1]));
        monthIncome.setText(Double.toString(a[0]));

        budgetMoney = Utility.selectBudget(new MySqlite(this));
        budget = findViewById(R.id.tv_budget);
        if(budgetMoney <= 0){
            budget.setText("点击设置");
            monthBalance.setText("0.00");
        } else {
            budget.setText(Double.toString(budgetMoney));
            monthBalance.setText(Double.toString(budgetMoney-a[1] + a[0]));
        }
        budget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyDialog myDialog = new MyDialog(MainActivity.this);
                myDialog.setTitle("设置预算金额");
                myDialog.setHint("点击输入金额");
                myDialog.setInput(InputType.TYPE_CLASS_NUMBER);
                myDialog.setAddOnclickListener("确定", new MyDialog.onAddOnclickListener() {
                    @Override
                    public void onAddClick() {
                        Utility.updateBudget(new MySqlite(MainActivity.this),myDialog.getEditText());
                        budgetMoney = Utility.selectBudget(new MySqlite(MainActivity.this));
                        budget.setText(Double.toString(budgetMoney));
                        monthBalance.setText(Double.toString(budgetMoney-a[1] + a[0]));
                        myDialog.dismiss();
                    }
                });
                myDialog.show();
            }
        });
        lFather = findViewById(R.id.lv_father);
        lFather.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return displays.size();
            }

            @Override
            public Object getItem(int i) {
                return displays.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                view = View.inflate(MainActivity.this, R.layout.list_father, null);
                TextView date = view.findViewById(R.id.tv_date);
                TextView expend = view.findViewById(R.id.tv_expend);
                TextView week = view.findViewById(R.id.tv_week);
                TextView income = view.findViewById(R.id.tv_income);
                ArrayList<AccountBook> list = displays.get(i).getAccountBooks();
                date.setText(displays.get(i).getDate());
                expend.setText(Double.toString(getExpend(list)[1]));
                income.setText(Double.toString(getExpend(list)[0]));
                week.setText(list.get(0).getWeek());
                ListView lSon = view.findViewById(R.id.lv_son);
                lSon.setAdapter(new BaseAdapter() {
                    @Override
                    public int getCount() {
                        return list.size();
                    }

                    @Override
                    public Object getItem(int i) {
                        return list.get(i);
                    }

                    @Override
                    public long getItemId(int i) {
                        return i;
                    }

                    @Override
                    public View getView(int i, View view, ViewGroup viewGroup) {
                        view = View.inflate(MainActivity.this, R.layout.list_son, null);
                        TextView consumptionItem = view.findViewById(R.id.tv_consumptionItem);
                        TextView amount = view.findViewById(R.id.tv_amount);
                        TextView consumer = view.findViewById(R.id.tv_consumer);
                        consumer.setText(Utility.selectNameById(new MySqlite(MainActivity.this), list.get(i).getConsumerId()));
                        amount.setText(Double.toString(list.get(i).getAmount()));
                        consumptionItem.setText(list.get(i).getConsumption_item());
                        return view;
                    }
                });
                Utility.setListViewHeightBasedOnChildren(lSon);

                lSon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        ArrayList<AccountBook> accountBooks = Utility.selectAll(new MySqlite(MainActivity.this));
                        Intent intent = new Intent(MainActivity.this, ItemActivity.class);
                        intent.putExtra("id", accountBooks.get(i).getId());
                        startActivity(intent);
                    }
                });

                return view;
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
            }
        });

        imageView = findViewById(R.id.imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                intent.putExtra("flag","back");
                startActivity(intent);
                finish();
            }
        });
    }

    private ArrayList<Display> getAllDisplay() {
        ArrayList<Display> displays = new ArrayList<>();
        ArrayList<AccountBook> accountBooks = Utility.selectAll(new MySqlite(this));
        if (accountBooks.size() != 0) {
            ArrayList<AccountBook> list = null;
            String s = "";
            for (AccountBook a : accountBooks) {
                String p = a.getDateToString().substring(0, 10);
                if (!s.equals(p)) {
                    if (list != null) {
                        String[] st = s.split("/");
                        displays.add(new Display(st[0] + "年" + st[1] + "月" + st[2] + "日", list));
                    }
                    s = p;
                    list = new ArrayList<>();
                    list.add(a);
                } else {
                    list.add(a);
                }
            }
            String[] st = s.split("/");
            displays.add(new Display(st[0] + "年" + st[1] + "月" + st[2] + "日", list));

        }
        return displays;
    }

    private double[] getMonthExpend() {
        ArrayList<AccountBook> accountBooks = Utility.selectAll(new MySqlite(this));
        ArrayList<AccountBook> list = new ArrayList<>();
        for (AccountBook b : accountBooks) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (b.getDate().getMonth() == LocalDateTime.now().getMonth())
                    list.add(b);
            }
        }
        if (list.size() != 0)
            return getExpend(list);
        else
            return new double[]{0, 0};
    }

    private double[] getExpend(ArrayList<AccountBook> list) {
        double[] a = new double[]{0, 0};
        if (list.size() != 0)
            for (AccountBook b : list) {
                if (b.getAmount() < 0)
                    a[1] += -b.getAmount();
                else
                    a[0] += b.getAmount();
            }
        return a;


    }

}